package ciservice

import (
	"errors"
	"fmt"
	"github.com/gogf/gf/encoding/gbase64"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtime"
	"go-middle/app/common/model/ci"
	"go-middle/app/common/model/ci_log"
	"go-middle/app/common/model/server_has_model"
	"go-middle/app/openapi/service/runner"
)

//GetCiLog 任务日志列表
func GetCiLog(param ci_log.SelectPageReq) (total int, out []*ci_log.Entity) {
	model := ci_log.Model
	if param.Search != "" {
		v := "%" + param.Search + "%"
		model = model.Where("title like ? or clone_url like ?", v, v)
	}
	if param.Status != "" {
		model = model.Where("status = ?", param.Status)
	}
	if param.ServerId != "" {
		model = model.Where("server_id = ?", param.ServerId)
	}
	total, err := model.Count()
	if err != nil {
		glog.Error(err)
		return
	}
	out, err = model.FieldsEx("result").
		Page(param.Page, param.Limit).
		Order("id desc").
		All()
	if err != nil {
		glog.Error(err)
		return
	}
	return
}

//GetCiList 任务列表
func GetCiList(param ci.SelectPageReq) (total int, out []*ci.Entity) {
	model := ci.Model
	if param.Search != "" {
		v := "%" + param.Search + "%"
		model = model.Where("title like ? or branch like ? or clone_url like ?", v, v, v)
	}
	if param.Status != "" {
		model = model.Where("status = ?", param.Status)
	}
	if param.ServerId != "" {
		model = model.As("a").InnerJoin(server_has_model.Table+" b", fmt.Sprintf("a.id=b.model_id and b.model='%s'", ci.Table))
	}
	total, err := model.Count()
	if err != nil {
		glog.Error(err)
		return
	}
	out, err = model.FieldsEx("password").
		Page(param.Page, param.Limit).
		Order("id desc").
		All()
	if err != nil {
		glog.Error(err)
		return
	}
	return
}

//SaveCi 保存任务
func SaveCi(info interface{}) error {
	add, ok1 := (info).(ci.ReqAdd)
	edit, ok2 := (info).(ci.ReqEdit)
	if !ok1 && !ok2 {
		return errors.New("参数类型错误")
	}
	if ok2 {
		mode, _ := ci.FindOne("id=?", edit.Id)
		cnt, _ := ci.Model.Where("branch=? and clone_url = ? and id<>?", edit.Branch, mode.CloneUrl, edit.Id).Count()
		if cnt > 0 {
			return errors.New("任务重复")
		}
		if edit.Password != "" {
			pwd, _ := runner.EnCrypt(edit.Password)
			mode.Password = gbase64.EncodeString(pwd)
		}
		//编辑
		mode.Title = edit.Title
		mode.Status = edit.Status
		mode.Branch = edit.Branch
		mode.CloneUrl = edit.CloneUrl
		mode.IsClone = edit.IsClone
		mode.Command = edit.Command
		mode.User = edit.User
		mode.NotifyEmail = edit.NotifyEmail
		mode.UpdateTime = gtime.Now().Unix()
		_, err := mode.Update()
		if err != nil {
			return err
		}
	} else {
		cnt, _ := ci.Model.Where("branch=? and clone_url = ?", add.Branch, add.CloneUrl).Count()
		if cnt > 0 {
			return errors.New("任务重复")
		}
		var mode ci.Entity
		if add.Password != "" {
			pwd, _ := runner.EnCrypt(add.Password)
			mode.Password = gbase64.EncodeString(pwd)
		}
		//新增
		mode.Title = add.Title
		mode.Status = add.Status
		mode.Branch = add.Branch
		mode.CloneUrl = add.CloneUrl
		mode.IsClone = add.IsClone
		mode.Command = add.Command
		mode.User = add.User
		mode.NotifyEmail = add.NotifyEmail
		mode.CreateTime = gtime.Now().Unix()
		mode.UpdateTime = gtime.Now().Unix()
		_, err := mode.Insert()
		if err != nil {
			return err
		}
	}
	return nil
}

//DeleteCi 删除任务
func DeleteCi(ids []int64) error {
	tx, err := g.DB().Begin()
	if err == nil {
		_, err = ci.Model.TX(tx).Where("id in (?)", ids).Delete()
		if err != nil {
			glog.Error(err)
			_ = tx.Rollback()
			return err
		}
		_, err = server_has_model.Model.Where("model_id in (?) and model=?", ids, ci.Table).Delete()
		if err != nil {
			glog.Error(err)
			_ = tx.Rollback()
			return err
		}
		err = tx.Commit()
		if err != nil {
			return err
		}
	}
	return err
}

//GetCiByID 根据ID获取任务
func GetCiByID(id int64) *ci.Entity {
	res, _ := ci.Model.FindOne("id=?", id)
	return res
}
